<template>
  <div>
    <vxe-modal ref="xModal" v-model="isShowAddOrUpdateEmployeeModal" title="编辑&保存" width="800" :zIndex="999" resize destroy-on-close>
      <vxe-form ref="xForm" :data="formData" :rules="formRules" title-align="right" title-width="100" @submit="submitEvent">
        <vxe-form-item title="产品信息" span="24" title-align="left" title-width="200px" :title-prefix="{icon: 'fa fa-address-card-o'}"></vxe-form-item>
        <vxe-form-item title="分类" field="category" span="12" :item-render="{name: 'Cascader', attrs: {disabled: isShowDetail}, props: {filterable: true, data: categoryList}}"></vxe-form-item>
        <vxe-form-item title="名称" field="name" span="12" :item-render="{name: 'input', attrs: inputAttrs}"></vxe-form-item>
        <vxe-form-item title="规格" field="specification" span="12" :item-render="{name: 'input', attrs: inputAttrs}"></vxe-form-item>
        <vxe-form-item title="规格书编号" field="specNo" span="12" :item-render="{name: 'input', attrs: inputAttrs}"></vxe-form-item>
        <vxe-form-item title="单位" field="unit" span="12" :item-render="{name: 'input', attrs: inputAttrs}"></vxe-form-item>
        <vxe-form-item title="采购单价" field="purchasePrice" span="12" :item-render="{name: 'input', attrs: inputAttrs}"></vxe-form-item>
        <vxe-form-item title="标签" span="24">
          <vxe-checkbox-group v-model="formData.tags">
            <vxe-checkbox v-for="item in tagList" :key="item.value" :label="item.value" :disabled="isShowDetail">{{ item.label }}</vxe-checkbox>
          </vxe-checkbox-group>
        </vxe-form-item>
        <vxe-form-item title="备注" field="remark" span="24" :item-render="{name: 'input', attrs: inputAttrs}"></vxe-form-item>
        <vxe-form-item align="center" span="24" :visible-method="isDetail">
          <vxe-button type="submit" status="primary">保存</vxe-button>
          <vxe-button type="reset">重置</vxe-button>
          <vxe-button @click="close()">取消</vxe-button>
        </vxe-form-item>
      </vxe-form>
    </vxe-modal>
  </div>
</template>
<script>
import { productApi } from '@/api/product/product';
import { productTagApi } from '@/api/product/product-tag'
import { productCategoryApi } from '@/api/product/product-category'
export default {
  name: 'ProductTableAdd',
  components: {
  },
  props: {
  },
  data() {
    return {
      isShowAddOrUpdateEmployeeModal: false,
      isShowLoading: false,
      categoryList: [],
      tagList: [],
      isShowDetail: false,
      inputAttrs: {
        placeholder: '请输入', 
        disabled: false
      },
      formData: {
        id: 0,
        name: '',
        specification: '',
        specNo: '',
        unit: '',
        purchasePrice: 0,
        tags: [],
        remark: '',
        category: []
      },
      formRules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        mobilePhone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            pattern: /^(13|14|15|16|17|18)\d{9}$/,
            message: '手机号格式错误',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  computed: {},
  watch: {
  },
  filters: {},
  created() {
    this.getCategoryList();
    this.getTagList();
  },
  mounted() {
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  methods: {
    // 打开Modal
    showModal(row, isDetail) {
      if (isDetail !== undefined && isDetail) {
        this.isShowDetail = isDetail;
        this.inputAttrs.placeholder = '';
        this.inputAttrs.disabled = true;
      } else {
        this.isShowDetail = false;
        this.inputAttrs.placeholder = '请输入';
        this.inputAttrs.disabled = false;
      }
      if (row && Object.keys(row).length > 0) {
        this.formData = Object.assign({}, row);
        let tags = [];
        row.tags.split(',').forEach(element => {
          tags.push(parseInt(element));
        });
        this.formData.tags = tags;
        let category = [];
        console.log(row.categoryPath != 0 && row.categoryPath != '');
        if (row.categoryPath != 0 && row.categoryPath != '') {
          row.categoryPath.split(',').forEach(element => {
            category.push(element + '');
          });
        }
        console.log(category);
        this.formData.category = category;       
      } else {
        this.formData = {};
      }
      this.isShowAddOrUpdateEmployeeModal = true;
    },
    // isDetail
    isDetail({data, property}) {
      return !this.isShowDetail;
    },
    close() {
      this.$Modal.confirm({
        title: '友情提醒',
        content: '确定要关闭吗?关闭后表单会被重置!',
        onOk: () => {
          this.$refs.xModal.close();
        }
      });
    },
    // 点击提交
    submitEvent() {
      if (this.formData.id) {
        this.update(this.formData);
      } else {
        this.add(this.formData);
      }
    },
    // 修改成员
    async update(data) {
      try {
        let reqData = Object.assign({}, data);
        if (data.tags !== undefined) {
          reqData.tags = data.tags.join(',');
        }
        if (data.category !== undefined) {
          reqData.category = data.category[(data.category.length - 1)];
        }
        this.isShowLoading = true;
        let result = await productApi.update(reqData);
        this.isShowAddOrUpdateEmployeeModal = false;
        this.$Message.success('修改成功');
        this.$emit('addSuccess');
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      } finally {
        this.isShowLoading = false;
      }
    },
    // 添加新用户接口
    async add(data) {
      try {
        let reqData = Object.assign({}, data);
        if (data.tags !== undefined) {
          reqData.tags = data.tags.join(',');
        }
        if (data.category !== undefined) {
          reqData.category = data.category[(data.category.length - 1)];
        }
        this.isShowLoading = true;
        let result = await productApi.add(reqData);
        this.isShowAddOrUpdateEmployeeModal = false;
        this.$Message.success('添加成功');
        this.$emit('addSuccess');
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      } finally {
        this.isShowLoading = false;
      }
    },
    getCategoryList() {
      productCategoryApi.getTree().then((response) => {
        this.categoryList = this.getCategoryTree(response.data);
      }).catch(error => {

      });
    },
    getCategoryTree(categoryList) {
      let cateList = [];
      if (categoryList.length <= 0) {
        return cateList;
      }
      categoryList.forEach(element => {
        let cate = {
          value: element.id + '',
          label: element.category,
          children: []
        };
        if (element.children && element.children.length > 0) {
           cate.children = this.getCategoryTree(element.children);
        }
        cateList.push(cate);
      });
      return cateList;
    },
    getTagList() {
      productTagApi.getAll().then((response) => {
        let tagList = [];
        response.data.forEach(element => {
          tagList.push({
            value: element.id,
            label: element.tag 
          });
        });
        this.tagList = tagList;
      }).catch(error => {

      });
    }
  }
};
</script>
